package com.biostime.dingdingbox.modules.sys.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.biostime.dingdingbox.common.config.Global;
import com.biostime.dingdingbox.common.persistence.Page;
import com.biostime.dingdingbox.common.utils.StringUtils;
import com.biostime.dingdingbox.common.web.BaseController;
import com.biostime.dingdingbox.modules.sys.entity.Log;
import com.biostime.dingdingbox.modules.sys.service.LogService;

/**
 * 日志表Controller
 * @author chenweicheng
 * @version 2016-04-11
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/log")
public class LogController extends BaseController {

	@Autowired
	private LogService logService;
	
	@ModelAttribute
	public Log get(@RequestParam(required=false) String id) {
		Log entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = logService.get(id);
		}
		if (entity == null){
			entity = new Log();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:log:view")
	@RequestMapping(value = {"list", ""})
	public String list(Log log, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Log> page = logService.findPage(new Page<Log>(request, response), log); 
		model.addAttribute("page", page);
		return "modules/sys/logList";
	}

	@RequiresPermissions("sys:log:view")
	@RequestMapping(value = "form")
	public String form(Log log, Model model) {
		model.addAttribute("log", log);
		return "modules/sys/logForm";
	}

	@RequiresPermissions("sys:log:edit")
	@RequestMapping(value = "save")
	public String save(Log log, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, log)){
			return form(log, model);
		}
		logService.save(log);
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+Global.getAdminPath()+"/sys/log/?repage";
	}
	
	@RequiresPermissions("sys:log:edit")
	@RequestMapping(value = "delete")
	public String delete(@RequestParam(value="ids",required=false) String idsRequest, Log log, RedirectAttributes redirectAttributes) {
		//批量删除
		if(!StringUtils.isEmpty(idsRequest)){
			String[] ids = idsRequest.split(",");
			for(String id : ids){
				logService.delete(new Log());
			}
		}else{
			logService.delete(log);
		}
		
		addMessage(redirectAttributes, "删除成功");
		return "redirect:"+Global.getAdminPath()+"/sys/log/?repage";
	}

}